package com.xul.controller;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.xul.entity.Subject;
import com.xul.service.SubjectService;
import com.xul.utils.MapController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author xul
 * @create 2021-06-22 15:45
 */
@Controller
@RequestMapping("subject")
public class SubjectController {

    private final String LIST = "subject/list";
    private final String ADD = "subject/add";
    private final String UPDATE = "subject/update";

    @Autowired
    private SubjectService subjectService;

    @GetMapping("add")
    public String add() {
        return ADD;
    }

    @PostMapping("create")
    @ResponseBody
    public Map<String, Object> create(Subject subject) {
        int result = subjectService.create(subject);
        if (result <= 0) {
            return MapController.getInstance().error().getMap();
        }
        return MapController.getInstance().success().getMap();
    }

    @PostMapping("delete/{id}")
    @ResponseBody
    public Map<String, Object> delete(@PathVariable("id") Integer id) {
        int result = subjectService.delete(id);
        if (result <= 0) {
            return MapController.getInstance().error().getMap();
        }
        return MapController.getInstance().success().getMap();
    }

    @PostMapping("delete")
    @ResponseBody
    public Map<String, Object> delete(String ids) {
        int result = subjectService.delete(ids);
        if (result <= 0) {
            return MapController.getInstance().error().getMap();
        }
        return MapController.getInstance().success().getMap();
    }

    @PostMapping("update")
    @ResponseBody
    public Map<String, Object> update(@RequestBody Subject subject) {
        int result = subjectService.update(subject);
        if (result <= 0) {
            return MapController.getInstance().error().getMap();
        }
        return MapController.getInstance().success().getMap();
    }

    @GetMapping("detail/{id}")
    public String detail(@PathVariable("id") Integer id, ModelMap modelMap) {
        Subject subject = subjectService.detail(id);
        modelMap.addAttribute("subject", subject);
        return UPDATE;
    }


    @PostMapping("query")
    @ResponseBody
    public Map<String, Object> query(@RequestBody Subject subject) {
        List<Subject> list = subjectService.query(subject);
        Integer count = subjectService.count(subject);
        return MapController.getInstance().success().put("data", list).put("count", count).getMap();
    }

    @GetMapping("list")
    public String list() {
        return LIST;
    }
}
